package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.ldgs.*;
import com.app.service.LdgsService;
import com.app.service.UploadParameterService;
import com.app.service.YjDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 马山梁场
 */
@Slf4j
@RestController
@RequestMapping("/ldbb")
public class LdgsbbyhlcUploadController {
    @Value("${yj.ldgsbbyhlc.getTokenHost}")
    private String getTokenHost;
    @Value("${yj.ldgsbbyhlc.clientId}")
    private String clientId;
    @Value("${yj.ldgsbbyhlc.doMudjackMaininfoHost}")
    private String doMudjackMaininfoHost;
    @Value("${yj.ldgsbbyhlc.mudjackDataHost}")
    private String mudjackDataHost;
    @Value("${yj.ldgsbbyhlc.mudjackDataDetailHost}")
    private String mudjackDataDetailHost;
    private static final String SUCCESS_STATE = "1";
    private static final String FAIL_STATE = "0";
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    LdgsService ldgsService;


    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException, UnsupportedEncodingException {
        ExternalResponse externalResponse;
        try {
            // 参数校验
            if (ids == null || ids.length == 0) {
                return new ExternalResponse(0, "未选择任何数据", "");
            }

            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("companyEn", "ql");
            tokenMap.put("functoinName", "压浆");
            tokenMap.put("clientId", clientId);

            ResponseData responseData = ldgsService.getToken(getTokenHost, tokenMap);
            if (responseData == null || !responseData.isSuccess() || 0 != responseData.getCode()) {
                return new ExternalResponse(0, "token过期", "");
            }

            AuthToken authToken = JSONObject.parseObject(responseData.getResult().toString(), AuthToken.class);
            String token = authToken.getToken();
            if (token == null || token.isEmpty()) {
                return new ExternalResponse(0, "获取token失败", "");
            }

            List<YjData> yjDataList = yjDataService.findList(ids);
            if (yjDataList == null || yjDataList.isEmpty()) {
                return new ExternalResponse(0, "未找到对应数据", "");
            }

            List<List<YjData>> groupList = yjDataList.stream()
                    .collect(Collectors.groupingBy(YjData::getBridge_code, Collectors.toList()))
                    .values().stream().collect(Collectors.toList());

            UploadParameter uploadParameter = uploadParameterService.findOne("45");
            HashMap<String, String> headerMap = new HashMap<>();
            headerMap.put("X-Access-Token", token);

            AtomicInteger succTotal = new AtomicInteger();
            AtomicInteger failTotal = new AtomicInteger();
            StringBuilder responseContent = new StringBuilder("本次共上传数据：【").append(ids.length).append("】条,");

            for (List<YjData> dataList : groupList) {
                List<Integer> userIds = dataList.stream().map(YjData::getId).collect(Collectors.toList());
                MainMudjack mainMudjack = ldgsService.getMainMudjack(dataList, uploadParameter);
                if (mainMudjack == null || mainMudjack.getMainId() == null) {
                    log.warn("主表构建失败，跳过该批次数据: {}", dataList);
                    failTotal.addAndGet(userIds.size());
                    continue;
                }

                String mainJson = JSON.toJSONString(mainMudjack);
                log.info("发送主表数据：{}", mainJson);
                ResponseData mainResult = ldgsService.sendData(doMudjackMaininfoHost, mainJson, headerMap);
                if (mainResult == null || !mainResult.isSuccess() || mainResult.getCode() != 0) {
                    log.warn("主表上传失败，code={}, msg={}", mainResult != null ? mainResult.getCode() : "null", mainResult != null ? mainResult.getMessage() : "");
                    failTotal.addAndGet(userIds.size());
                    continue;
                }

                List<MudjackData> mudjackDataList = ldgsService.getMudjackData(dataList, uploadParameter, mainMudjack.getMainId());
                String dataJson = JSON.toJSONString(mudjackDataList);
                log.info("发送子表数据：{}", dataJson);
                ResponseData dataResult = ldgsService.sendData(mudjackDataHost + "?mainId=" + mainMudjack.getMainId(), dataJson, headerMap);
                if (dataResult == null || !dataResult.isSuccess() || dataResult.getCode() != 0) {
                    log.warn("子表上传失败，code={}, msg={}", dataResult != null ? dataResult.getCode() : "null", dataResult != null ? dataResult.getMessage() : "");
                    failTotal.addAndGet(userIds.size());
                    continue;
                }

                int count = 0;
                for (MudjackData mudjackData : mudjackDataList) {
                    String holeId = mudjackData.getHoleId();
                    if (holeId == null || holeId.isEmpty()) {
                        log.warn("holeId为空，跳过曲线上传");
                        continue;
                    }

                    List<MudjackProcessData> processDataList = ldgsService.getMudjackProcessData(mudjackData, uploadParameter);
                    String processJson = JSON.toJSONString(processDataList);
                    log.info("发送曲线数据：{}", processJson);
                    ResponseData processResult = ldgsService.sendData(mudjackDataDetailHost + "?holeId=" + holeId, processJson, headerMap);
                    if (processResult != null && processResult.isSuccess() && 0 == processResult.getCode()) {
                        count++;
                    }
                }

                if (count == mudjackDataList.size()) {
                    userIds.forEach(userId -> {
                        boolean success = ldgsService.updateState(SUCCESS_STATE, String.valueOf(userId));
                        if (success) {
                            succTotal.incrementAndGet();
                        } else {
                            failTotal.incrementAndGet();
                        }
                    });
                } else {
                    userIds.forEach(userId -> {
                        boolean success = ldgsService.updateState(FAIL_STATE, String.valueOf(userId));
                        if (success) {
                            failTotal.incrementAndGet();
                        } else {
                            // 记录更新失败的情况
                            log.warn("状态更新失败，userId={}", userId);
                            failTotal.incrementAndGet();
                        }
                    });
                }
            }
            responseContent.append("成功【").append(succTotal.get()).append("】条,失败").append(failTotal.get()).append("条");
            externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        } catch (Exception e) {
            log.error("上传过程中发生异常：", e);
            externalResponse = new ExternalResponse(0, "上传过程中发生错误", "");
        }
        return externalResponse;
    }


}